package com.ht.sps.web.view;

import org.nutz.lang.Streams;
import org.nutz.mvc.View;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 图片视图, 用于显示保存在WEB-INF下面的图片或音频文件, 要求文件名中的.改为_:如test.png,改为test_png
 *
 * @author: 薄成文 13-12-6 上午10:01
 * To change this template use File | Settings | File Templates.
 */
public class MimeView implements View {
    private static final Logger log = LoggerFactory.getLogger(MimeView.class);
    public static final String MIME_JPEG = "image/jpeg";
    public static final String MIME_PNG = "image/png";
    public static final String MIME_WAV = "audio/x-wav";

    private String contentType = MIME_JPEG;
    private File file;

    public MimeView(String filePath) {

        file = new File(filePath);
        if (file.exists()) {
            String fileName = file.getName().toLowerCase();
            if (fileName.endsWith("jpg") || fileName.endsWith("jpeg")) {
                this.contentType = MIME_JPEG;
            } else if (fileName.endsWith("png")) {
                this.contentType = MIME_PNG;
            }
        }
    }

    @Override
    public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable {
        resp.setContentType(this.contentType);
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        OutputStream out = resp.getOutputStream();
        if (file.exists()) {
            InputStream in = Streams.fileIn(file);
            Streams.write(out, in);

            in.close();
        }
        // 以下关闭输入流！
        out.flush();
        out.close();

    }
}
